package cn.org.mrliu.ssm.common.web.interceptor;

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 请求控制器的拦截器:输出请求信息
 * 
 * @author MrLiu
 *
 */
public class RequestControllerInterceptor extends HandlerInterceptorAdapter {
	private static Logger log = LoggerFactory.getLogger(RequestControllerInterceptor.class);
	private static final String SPACE = "  ";
	private static final String LOG_LEVEL_DEBUG = "debug";
	// private static final String LOG_LEVEL_INFO = "info";

	private boolean enabled = true; // 是否启用,默认启用
	private String logLevel = LOG_LEVEL_DEBUG; // 日志级别,默认为debug

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 如果不启用,则跳出,继续执行下一个拦截器
		if (!enabled) {
			return true;
		}
		// 如果访问的不是控制器,则跳出,继续执行下一个拦截器
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		log("---------------------------------- request start ----------------------------------");
		log("path:" + request.getServletPath());
		log("target:" + handler);
		log("controller:" + handlerMethod.getBeanType().getSimpleName());
		log("method:" + handlerMethod.getMethod().getName());
		Map<String, String[]> paramsMap = request.getParameterMap();
		int paramSize = paramsMap.size();
		if (paramsMap != null && paramSize > 0) {
			log("params(" + paramSize + "):");
			int i = 0;
			for (Entry<String, String[]> kv : paramsMap.entrySet()) {
				i++;
				String key = kv.getKey();
				String[] values = kv.getValue();
				String string = SPACE + i + " ";
				if (values == null) { // 没有值
					string += key;
				} else if (values.length > 1) { // 多个值
					string += key + ":" + Arrays.toString(values);
				} else { // 一个值
					string += key + ":" + values[0];
				}
				log(string);
			}
		}
		
		
//		String contentType= request.getContentType();
//		if ("application/json".equals(contentType)) {
//			String string = IOUtils.toString(request.getInputStream());
//			System.out.println(string);
//			JSONObject jsonObject = JSON.parseObject(string);
//			System.out.println(JSON.toJSONString(jsonObject,true));
//		}
		
		log("---------------------------------- request end ----------------------------------");
		return true;
	}

	private void log(String msg) {
		if (LOG_LEVEL_DEBUG.equals(logLevel)) {
			log.debug(msg);
		} else {
			log.info(msg);
		}
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public void setLogLevel(String logLevel) {
		this.logLevel = logLevel;
	}
}
